<template>
  <div>
    <vxe-form ref="form" :data="form" v-bind="$attrs" :items="formItems" :rules="formRules" title-align="right"
      title-width="110">


      <template #file="{ data }">
        <div class="fileBox">
          <vxe-button status="primary" size="mini" @click="openUpload">选择文件</vxe-button>
          <div v-if="data.fileList && data.fileList.length > 0" class="anthorContent-item-fileList">

            <div v-for="item in data.fileList" :key="item.fileUrl" class="fileList-item">
              <i class="el-icon-paperclip fileList-item-beforeIcon"></i>
              <span class="fileList-item-filename">{{ item.fileName }}</span>
              <i class="el-icon-close pointer fileList-item-afterIcon" @click="delFile(item)"></i>
            </div>

          </div>
        </div>
      </template>
      <template #fileWidthTemplate="{ data }">
        <div class="fileBox">
          <vxe-button status="primary" size="mini" @click="openUpload">选择文件</vxe-button>
          <div v-if="data.fileList && data.fileList.length > 0" class="anthorContent-item-fileList">
            <div v-for="item in data.fileList" :key="item.fileUrl" class="fileList-item">
              <i class="el-icon-paperclip fileList-item-beforeIcon"></i><span class="fileList-item-filename">{{
                item.fileName }}</span>
              <i class="el-icon-close pointer fileList-item-afterIcon" @click="delFile(item)"></i>
            </div>
          </div>
          <vxe-button status="primary" size="mini" @click="openDownload">模板下载</vxe-button>
        </div>
      </template>
    </vxe-form>
    <SelectFromTableDialog width="90%" ref="selectTable" v-bind="options" @search="getTableList" @pager="getTableList"
      @submit="getSelected" />
    <SelectFromTreeTableDialog ref="treeTable" :isContractPrice="isContractPrice" isEdit v-bind="options"
      :contractId="contractId" :infoId="infoId" v-model="value.checkParams" @search="refreshStd" @refreshStd="refreshStd"
      @submit="selParam" />
  </div>
</template>
<script>
import VXETable from 'vxe-table';
import SelectFromTableDialog from '/@/components/SelectFromTableDialog';
import SelectFromTreeTableDialog from '/@/components/SelectFromTreeTableDialog';
import util from '@/util/util';
import { v4 as uuidv4 } from 'uuid';
export default {
  components: { SelectFromTableDialog, SelectFromTreeTableDialog },
  props: {
    // endDate: item.endDate,
    value: {
      type: Object,
      default: () => { },
    },
    formOptions: {
      column: 3, // 列数
      items: [], // 项
    },
    isContractPrice: {
      type: Boolean,
      default: false,
    },
    contractId: {
      type: [String, Number],
      default: '',
    },
    infoId: {
      type: [String, Number], 
      default: '',
    },
    formRules: {
      type: Object,
      default: () => { },
    },
  },
  data() {
    return {
      contract: {
        title: '合同列表',
        type: 'radio',
        searchConfig: [
          {
            label: '合同编号',
            field: 'contractNumber',
          },
          {
            label: '合同名称',
            field: 'contractName',
          },
        ],
        columns: [
          {
            type: 'radio',
            title: '',
            width: 60,
            editRender: {},
          },
          {
            field: 'contractNumber',
            title: '合同编号',
            editRender: {},
          },
          {
            field: 'contractName',
            title: '合同名称',
            editRender: {},
          },
          {
            field: 'pricingType',
            title: '定价方式',
            editRender: {},
            formatter: ({ cellValue }) => {
              return this.matterContractType(cellValue);
            },
          },
          {
            field: 'customerName',
            title: '委托方',
            editRender: {},
          },
          {
            field: 'contractSigningDate',
            title: '委托时间',
            editRender: {},
            slots: {
              default: (params, h) => {
                return h('span', [util.parseTime(params.row.contractSigningDate, '{y}-{m}-{d}')]);
              },
            },
          },
          {
            field: 'contractFinishDate',
            title: '完成时间',
            editRender: {},
            slots: {
              default: (params, h) => {
                return h('span', [util.parseTime(params.row.contractFinishDate, '{y}-{m}-{d}')]);
              },
            },
          },
          {
            field: 'contractStatus',
            title: '合同完成状态',
            editRender: {},
            slots: {
              default: (params, h) => {
                return h('span', [this.getContractStatus(params.row.contractStatus)]);
              },
            },
          },
        ],
        tableData: [],
        total: 0,
      },
      customer: {
        title: '客户列表',
        type: 'radio',
        searchConfig: [
          {
            label: '单位名称',
            field: 'companyName',
          },
        ],
        columns: [
          {
            type: 'radio',
            title: '',
            width: 60,
            editRender: {},
          },
          {
            field: 'companyName',
            title: '单位名称',
            editRender: {},
          },
          {
            field: 'contactsName',
            title: '负责人',
            editRender: {},
          },
          {
            field: 'contactsInfo',
            title: '联系方式',
            editRender: {},
          },
        ],
        tableData: [],
        total: 0,
      },
      project: {
        title: '新增检测项目',
        type: 'radio',
        columns: [
          {
            field: 'name',
            type: 'checkbox',
            treeNode: true,
            title: '检测项目 / 检测参数',
            editRender: {},
            minWidth: 100,
            slots: {
              default: 'd_itemName',
              // edit: 'e_itemName',
            },
          },
          {
            field: 'itemShortName',
            title: '项目编号拼音简称',
            editRender: {},
          },

          {
            field: 'salesUnit',
            title: '计价单位',
            width: 80,
            align: 'center',
            editRender: {},
          },
          {
            field: 'unitPrice',
            title: '单价(元)',
            align: 'center',
            width: 100,
            editRender: {},
          },
          {
            field: 'domainNames',
            title: '检测领域',
            editRender: {},
          },
          {
            field: 'detectionStdList',
            title: '检测标准',
            editRender: {},
            width: 150,
            slots: {
              default: 'd_detectionStdList',
              edit: 'e_detectionStdList',
            },
          },
          {
            field: 'workingHours',
            title: '工时',
            align: 'center',
            width: 80,
            editRender: {},
          },
          {
            field: 'remarks',
            title: '备注',
            editRender: {},
          },
        ],
        tableData: [],
        total: 0,
      },
      keyName: 'contract',
      fileId: null,
    };
  },
  computed: {
    formItems() {
      if (!this.formOptions.column) {
        VXETable.modal.message({
          content: '不要忘记输入列数',
          status: 'error',
        });
        return;
      }
      if (!this.formOptions.items || this.formOptions.items.length === 0) {
        VXETable.modal.message({
          content: '不要忘记输入配置项',
          status: 'error',
        });
        return;
      }
      const type = {
        upload: 'button',
        selectTable: 'input',
        date: 'input',
      };
      const formItems = [
        {
          span: 24,
          children: this.formOptions.items.map((item) => {
            // console.log(item, 6)
            return {
              title: item.title, // label
              field: item.field, // 字段
              folding: item.folding,
              span: item.isOneLine ? 24 : 24 / parseInt(this.formOptions.column), // 占span/24的位置
              itemRender: {
                name: `$${type[item.type] ? type[item.type] : item.type}`,
                options: item.options || null,
                defaultValue: item.value,
                props: {
                  type: item.type,
                  placeholder: item.type === 'input' ? `请输入${item.title}` : `请选择${item.title}`,
                  readonly: item.readonly || item.type === 'selectTable',
                  disabled: item.disabled,
                  content: item.content,
                  status: item.status,
                  size: item.size,
                  value: item.value,
                  'disabled-method': item.disabledMethod
                },
                events: {
                  click:
                    item.type === 'selectTable'
                      ? () => {
                        this.openDialog(item.prop);
                      }
                      : item.event
                        ? () => { item.event() }
                        : function () { },
                },
              },
              slots: item.slots,
            };
          }),
        },
      ];
      return formItems;
    },
    options() {
      return this[this.keyName];
    },
    form() {
      return this.value;
    },
    validParams() {
      const params = Object.keys(this.formRules || {});
      return params.map((key) => {
        return this.form[key];
      });
    },
  },
  watch: {
    validParams() {
      // 暂时手动清除校验状态，有没有更好的办法？
      this.$refs.form.validate().catch((errMap) => errMap);
    },
  },
  mounted() { },
  methods: {
    getContractStatus(val) {
      return val === 'COMPLETED' ? '完成' : '未完成';
    },
    matterContractType(val) {
      return val === 'CONTRACT_PRICE' ? '合同定价' : '标准定价';
    },
    getContractList(params = { page: 1, size: 10 }) {
      this.$api.getContractList({ ...params, contractStatus: 'IN_PROGRESS' }).then((res) => {
        this.contract.tableData = res.data.list;
        this.contract.total = res.data.total;
      });
    },
    getCustomerList(params = { page: 1, size: 10 }) {
      this.$api.getCustomerPage(params).then((res) => {
        this.customer.tableData = res.data.list;
        this.customer.total = res.data.total;
      });
    },
    getChargeStd(params) {
      this.isContractPrice ? this.getChargeStdItemList(params) : this.getChargeStdList(params);
    },
    getChargeStdList(params = { infoId: null }) {
      this.$api
        .getChargeStdDetail({
          infoId: params.infoId,
          itemName: params.itemName,
        })
        .then((res) => {
          const { chargeStdItemList } = res.data;
          const data = {};
          this.form.tableData.forEach((item) => {
            item.detectionStdList.forEach((it) => {
              data[item.paramId] = it;
            });
          });
          chargeStdItemList.forEach((item) => {
            item.chargeStdParamList.forEach((it) => {
              it.detectionStdList = [];
              const second = data[it.id];
              if (second) {
                it.detectionStdList = [second];
              }
            });
          });
          this.project.tableData = chargeStdItemList;
        });
    },
    getChargeStdItemList(params = { contractId: null, infoId: null }) {
      this.$api
        .getChargeStdItemList({
          ...params,
        })
        .then((res) => {
          const data = {};
          this.form.tableData.forEach((item) => {
            item.detectionStdList.forEach((it) => {
              data[item.paramId] = it;
            });
          });
          res.data.forEach((item) => {
            item.chargeStdParamList.forEach((it) => {
              it.detectionStdList = [];
              const second = data[it.paramId];
              if (second) {
                it.detectionStdList = [second];
                it.detectionStdIds = [second.id];
              }
            });
          });
          this.project.tableData = res.data;
        });
    },
    openDownload() {
      this.$emit('download');
    },
    openDialog(prop) {
      this.keyName = prop;
      switch (prop) {
        case 'contract':
          this.getContractList();
          this.$refs.selectTable.dialogVisible = true;
          break;
        case 'customer':
          this.getCustomerList();
          this.$refs.selectTable.dialogVisible = true;
          break;
        case 'project':
          // this.getChargeStd({ contractId: this.contractId, infoId: this.form.infoId });
          if (!this.contractId) {
            VXETable.modal.message({ status: 'error', content: `请先选择合同` });
            return;
          }
          this.$refs.treeTable.dialogVisible = true;
          break;
      }
    },
    async openUpload() {
      try {
        const { file } = await VXETable.readFile();
        let formData = new FormData();
        formData.append('file', file);
        const businessId = uuidv4();

        this.$api.fileUpload(this.fileId || businessId, formData).then((res) => {
          if (res.code == 0) {

            const { name: fileName, size: fileSize } = file;
            const fileObj = res.data.data ? res.data.data[0] : {};
            this.fileId = fileObj.objectId;
            // this.form.fileName = fileName;
            // this.form.fileSize = fileSize;
            // this.form.fileUrl = fileObj.filePath;
            console.log(this.form, this.form.fileList, 6)
            this.form.fileList.push({
              fileName,
              fileSize,
              fileUrl: fileObj.filePath
            })
            VXETable.modal.message({
              content: '上传成功',
              status: 'success',
            });
          }
        });
      } catch (e) { }
    },
    async delFile(file) {
      const type = await VXETable.modal.confirm(`确认删除${file.fileName}, 是否继续?`);
      if (type === 'confirm') {
        VXETable.modal.message({ status: 'success', content: `已删除` });
        // this.form.fileName = null;
        // this.form.fileSize = null;
        // this.form.fileUrl = null;
        this.form.fileList = this.form.fileList.filter(item => item.fileUrl !== file.fileUrl)
      }
    },
    getTableList(params) {
      switch (this.keyName) {
        case 'contract':
          this.getContractList(params);
          break;
        case 'customer':
          this.getCustomerList(params);
          break;
      }
    },
    getSelected(data) {
      switch (this.keyName) {
        case 'contract':
          this.form.contractId = data.id;
          this.form.infoId = data.chargeStdId;
          this.form.pricingType = data.pricingType;
          this.form.contractName = data.contractName;
          this.form.entrustDate = data.createTime;
          this.form.projectName = data.projectName;
          this.form.entrustName = data.customerName;
          break;
        case 'customer':
          this.form.entrustName = data.contactsName;
          break;
      }
    },
    refreshStd(data) {
      this.getChargeStd({ contractId: this.contractId, ...data });
    },
    selParam(result) {
      const selList = Array.isArray(result) ? result : [result];
      // this.checkParams = selList;
      this.$emit('getProject', selList);
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .vxe-select--panel.is--transfer {
    z-index: 2003 !important;
  }

  .fileBox {
    display: flex;
    align-items: center;
  }

  .anthorContent-item-fileList {
    margin-left: 5px;
    margin-right: 5px;

    .fileList-item {
      display: inline-block;
      height: 32px;
      line-height: 32px;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid #cccccc;
      padding: 0 10px;

      .fileList-item-filename {
        height: 100%;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.65);
        line-height: 22px;
        text-overflow: ellipsis;
      }

      .fileList-item-beforeIcon {
        color: #1f8fff;
        margin-right: 10px;
      }

      .fileList-item-afterIcon {
        margin-left: 10px;
      }
    }
  }
}
</style>
